package com.gscitysfy.cus.drain.modules.common.controller;

import com.gscitysfy.cus.drain.utils.HttpResponseUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @author 葛守跃
 * @version 1.0.0
 * @ClassName DownloadLocalFileController
 * @Description 云文件相关操作
 * @creatTime 2022/15 14:56
 */
@Tag(name = "通用接口", description = "本地文件操作通用接口")
@RestController
@RequestMapping("/common")
@Slf4j
public class DownloadLocalFileController {

    @Resource
    private ResourceLoader resourceLoader;

    /**
     * 下载本地文件接口
     * @param dir
     * @param filename
     * @return
     * @throws IOException
     */
    @Operation(summary = "下载resources目录下静态文件接口", description = "根据文件所在目录及文件名，下载文件")
    @GetMapping("/downloadLocalFile")
    public ResponseEntity<byte[]> downloadTemplate(String dir, String filename) throws IOException {
            String path = dir + File.separator + filename;
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);
            byte[] body = IOUtils.toByteArray(resource.getInputStream());
            HttpHeaders headers = HttpResponseUtil.getDownloadHeaders(filename);

            HttpStatus statusCode = HttpStatus.OK;
            return new ResponseEntity<>(body, headers, statusCode);
    }

}
